<?php
class articleModel extends RPHP_Model
{

    protected $_auth = null;

    //检查权限
    public function checkPriv($pv, $return = true, $menu = true)
    {
        $auth = $this->auth->CheckPriv($pv, $return, $menu);
        if ($return) {
            $this->_auth = $auth;
        }

        return $auth;
    }

    //getdocument
    public function getDocs($docid)
    {
        if (is_array($docid)) {
            $where = " WHERE `docid` IN (" . implode(",", array_unique($docid)) . ")";
        } else {
            $where = " WHERE `docid`=" . intval($docid);
        }

        $sql = "SELECT `docid`,`filename`,`create_time` FROM {$this->_prefix['primary']}documents " . $where;
        $rs  = $this->sql($sql);
        if ($rs) {
            foreach ($rs as $r) {
                $doc[$r['docid']] = $this->c['doc_host'] . date("Ymd", $r['create_time']) . "/" . date("H", $r['create_time']) . "/" . date("i", $r['create_time']) . "/" . $r['filename'];

            }
            return $doc;
        } else {
            return false;
        }

    }

    public function getNewDocs($docid)
    {
        $where = " WHERE `docid`=" . intval($docid);
        $sql   = "SELECT `docid`,`filename`,`create_time` FROM {$this->_prefix['primary']}documents " . $where;
        $rs    = $this->db->getrow($sql);
        if ($rs) {

            $file_url        = $this->c['doc_host'] . date("Ymd", $rs['create_time']) . "/" . date("H", $rs['create_time']) . "/" . date("i", $rs['create_time']) . "/" . $rs['filename'];
            $doc             = $rs;
            $doc['file_url'] = $file_url;
            return $doc;
        } else {
            return false;
        }

    }

    //获取单个商品
    public function getSingleArticle($article_id)
    {

        $sql  = "SELECT * FROM {$this->_prefix['primary']}article WHERE `article_id`=" . intval($article_id) . "   LIMIT 1";
        $data = $this->db->getrow($sql);

        return $data;

    }

    public function removeArticle($article_id)
    {
        $sql = "DELETE FROM {$this->_prefix['primary']}article WHERE `article_id`=" . intval($article_id) . "   LIMIT 1";
        return $this->sql($sql);
    }

    //商品列表
    public function getArticles($para, $page = 1, $pagesize = 10)
    {

        $where = " 1=1 ";

        if ($para['caid'] != '') {
            $where .= " AND `caid`=" . $para['caid'];
        }

        if ($para['keyword'] != '') {
            $where .= " AND (`title` LIKE '%" . $para['keyword'] . "%' OR `author` LIKE '%" . $para['keyword'] . "%') ";
        }

        $sql = "SELECT COUNT(`article_id`) AS `cnt` FROM {$this->_prefix['primary']}article WHERE " . $where;

        $cnt = $this->sql($sql);

        if ($cnt[0]['cnt'] > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "`add_time` DESC,`article_id` DESC";

            $sql = "SELECT `article_id`,`caid`,`title`,`author`,`add_time`,`is_open`,`level_type` FROM {$this->_prefix['primary']}article WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;

            $rs = $this->sql($sql);

        }

        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt[0]['cnt'] / $pagesize),
            'count'   => $cnt[0]['cnt'],
            'data'    => $rs,
            'para'    => $para,
        );
    }

    //保存文章
    public function saveArticle($da, $file, $article_id = 0)
    {

        $code                = 900;
        $savegoods           = true;
        $field['title']      = addslashes(htmlspecialchars(trim($da['title'])));
        $field['keywords']   = addslashes(htmlspecialchars(trim($da['keywords'])));
        $field['author']     = addslashes(htmlspecialchars(trim($da['author'])));
        $field['caid']       = intval($da['caid']);
        $field['is_open']    = intval($da['is_open']) == 1 ? 1 : 0;
        $field['content']    = addslashes(htmlspecialchars(trim($da['content'])));
        $field['recommend']  = intval($da['recommend']) == 1 ? 1 : 0;
        $field['hots']       = intval($da['hots']) == 1 ? 1 : 0;
        $field['urls']       = addslashes(trim($da['urls']));
        $field['level_type'] = intval($da['level_type']);

        //保存信息
        if ($field['title'] != "" && $savegoods) {
            $code = 403;
            //开始事务
            $this->db->begin();
            $rollback = true;
            //修改
            if ($article_id > 0) {
                $goods = $this->getSingleArticle($article_id);
                if ($goods) {

                    $field['update_time'] = $_SERVER['REQUEST_TIME'];

                    //修改文章
                    $sql = "UPDATE {$this->_prefix['primary']}article SET ";
                    foreach ($field as $key => $value) {
                        $upsql[] = "`" . $key . "`='" . $value . "'";
                    }
                    $sql .= implode(",", $upsql) . " WHERE `article_id`=" . $goods['article_id'];

                    $rcnum = $this->sql($sql);

                    if ($rcnum) {

                        $done = true;

                        if ($done) {
                            $code = 200;
                            $this->db->commit();
                            $rollback = false;
                        }
                    }
                } else {
                    $code = 404;
                }

            }
            //新增
            else {
                //其他必须字段
                $field['add_time'] = $_SERVER['REQUEST_TIME'];

                foreach ($field as $key => $value) {
                    $keys[]   = "`" . $key . "`";
                    $values[] = "'" . $value . "'";
                }

                //插入文章
                $sql = "INSERT INTO {$this->_prefix['primary']}article (" . implode(",", $keys) . ") VALUES (" . implode(",", $values) . ")";

                $article_id = $this->sql($sql);
                if ($article_id > 0) {
                    $done = true;
                    if ($done) {
                        $code = 200;
                        $this->db->commit();
                        $rollback = false;

                    }

                }

            } //end of add

            if ($rollback) {
                $this->db->rollback();
            }

        }
        return $code;
    }

    //获取所有类别
    public function getCategory($caid = 0, $isfucaid = false)
    {
        if ($isfucaid) {
            $tsql = " AND `fucaid`=" . intval($caid);
        } elseif ($caid > 0) {
            $tsql = " AND `caid`=" . intval($caid);
        }

        $sql = "SELECT * FROM {$this->_prefix['primary']}article_category WHERE  `stat`<3" . $tsql . " ORDER BY `fucaid` ASC,`sort` ASC";

        if ($caid > 0 && !$isfucaid) {
            $newdata = $this->db->getrow($sql);
        } else {
            $data = $this->sql($sql);
            if ($data) {
                if ($isfucaid) {
                    $newdata = $data;
                } else {
                    foreach ($data as $r) {
                        $newdata[$r['fucaid']][$r['caid']] = $r;
                    }
                }
            }
        }
        return $newdata;
    }

    //保存分类排序
    public function saveCategorySort($da)
    {
        $code = 900;
        if ($da['value'] != "") {
            $ids = json_decode($da['value']);
            foreach ($ids as $k => $r) {
                $sql = "UPDATE {$this->_prefix['primary']}article_category SET `sort`=" . $k . " WHERE `caid`=" . intval($r->id);
                $this->sql($sql);
            }
            $code = 200;
        }
        return $code;
    }

    //保存文档
    public function saveDocument($name, $filename, $filesize, $format, $create_time)
    {
        $sql = "INSERT INTO {$this->_prefix['primary']}documents
        (`name`,`filename`,`filesize`,`format`,`create_time`) VALUES
        ('" . $name . "','" . $filename . "'," . $filesize . ",'" . $format . "'," . $create_time . ")";

        $docid = $this->sql($sql);
        return $docid;
    }

    //保存分类
    public function saveCategory($da, $file, $caid = 0)
    {

        $code   = 900;
        $name   = addslashes(htmlspecialchars(trim($da['name'])));
        $stat   = intval($da['stat']);
        $fucaid = intval($da['fucaid']);

        //修改
        if ($caid > 0) {
            $sql = "SELECT * FROM {$this->_prefix['primary']}article_category WHERE `caid`=" . intval($caid) . "  AND `stat`<3";
            $rs  = $this->db->getrow($sql);

            if ($rs) {

                $sql = "UPDATE {$this->_prefix['primary']}article_category SET `stat`=" . $stat . ",`fucaid`=" . $fucaid . ",`name`='" . $name . "',`last_staffedit`=" . $_SERVER['REQUEST_TIME'] . " WHERE `caid`=" . $rs['caid'];
                $rd  = $this->sql($sql);
                if ($rd > 0) {
                    $code = 200;
                } else {
                    $code = 403;
                }

            } else {
                $code = 404;
            }
        }
        //新增
        else {
            if ($da['name'] != "") {

                $sql = "INSERT INTO {$this->_prefix['primary']}article_category
                    (`name`,`fucaid`,`stat`,`last_staffedit`) VALUES
                    ('" . $name . "'," . $fucaid . "," . $stat . "," . $_SERVER['REQUEST_TIME'] . ")";

                $rd = $this->sql($sql);

                if ($rd > 0) {
                    $code = 200;
                } else {
                    $code = 403;
                }

            }
        }
        return $code;

    }

    public function UploadPic($files)
    {
        $code = 706;
        //创建目录
        $dir['date'] = $this->c['upload']['dir'] . date("Ymd", $_SERVER['REQUEST_TIME']);
        if (!file_exists($dir['date'])) {
            mkdir($dir['date']);
        }

        $dir['hour'] = $dir['date'] . DIRECTORY_SEPARATOR . date("H", $_SERVER['REQUEST_TIME']);
        if (!file_exists($dir['hour'])) {
            mkdir($dir['hour']);
        }

        $dir['minute'] = $dir['hour'] . DIRECTORY_SEPARATOR . date("i", $_SERVER['REQUEST_TIME']);
        if (!file_exists($dir['minute'])) {
            mkdir($dir['minute']);
        }

        if (file_exists($dir['minute'])) {

            $doc_host = $this->c['doc_host'] . date("Ymd", $_SERVER['REQUEST_TIME']) . "/" . date("H", $_SERVER['REQUEST_TIME']) . "/" . date("i", $_SERVER['REQUEST_TIME']) . "/";

            foreach ($files['tmp_name'] as $k => $r) {

                if ($r != "") {
                    if (in_array($files['type'][$k], $this->c['upload']['mime'])) {

                        if ($files['size'][$k] <= $this->c['upload']['size']) {

                            $format = explode(".", $files['name'][$k]);
                            $format = strtolower($format[count($format) - 1]);

                            if (in_array($format, $this->c['upload']['fm'])) {

                                $filename = md5($_SERVER['REQUEST_TIME'] . $files['tmp_name'][$k] . $files['name'][$k]) . "." . $format;
                                $path     = $dir['minute'] . "/" . $filename;
                                if (move_uploaded_file($r, $path)) {

                                    $this->saveDocument($files['name'][$k], $filename, $files['size'][$k], $format, $_SERVER['REQUEST_TIME']);

                                    $data[$k] = '"' . $doc_host . $filename . '"';

                                } else {
                                    $error[$k] = 705;
                                }

                            } else {
                                $error[$k] = 703;
                            }

                        } else {
                            $error[$k] = 704;
                        }

                    } else {
                        $error[$k] = 703;
                    }

                } else {
                    $error[$k] = 702;
                }

                @unlink($r);

            }

        }
        return array('code' => $code, 'data' => $data, 'error' => $error);

    }
}
